from microbit import *

class LCD1602(object):
    def __init__(self, addr = 0x27):
        self.buf = bytearray(1)
        self.BK = 0x08
        self.RS = 0x00
        self.E = 0x04
        self.ADDR = addr
        self.setcmd(0x33)
        sleep(5)
        self.send(0x30)
        sleep(5)
        self.send(0x20)
        sleep(5)
        self.setcmd(0x28)
        self.setcmd(0x0C)
        self.setcmd(0x06)
        self.setcmd(0x01)

    def setReg(self, dat):
        self.buf[0] = dat
        i2c.write(self.ADDR, self.buf)
        sleep(1)

    def send(self, dat):
        d=dat&0xF0
        d|=self.BK
        d|=self.RS
        self.setReg(d)
        self.setReg(d|0x04)
        self.setReg(d)

    def setcmd(self, cmd):
        self.RS=0
        self.send(cmd)
        self.send(cmd<<4)

    def setdat(self, dat):
        self.RS=1
        self.send(dat)
        self.send(dat<<4)
        
    def backlight_on(self):
        self.BK=0x08
        self.setcmd(0)
     
    def backlight_off(self):
        self.BK=0
        self.setcmd(0)
        
    def clear(self):
        self.setcmd(1)

    def on(self):
        self.setcmd(0x0C)

    def off(self):
        self.setcmd(0x08)

    def show_char(self, ch, x=-1, y=0):
        if x>=0:
            a=0x80
            if y>0:
                a=0xC0
            a+=x
            self.setcmd(a)
        self.setdat(ch)

    def show_string(self, s, x=0, y=0):
        if len(s)>0:
            self.show_char(ord(s[0]),x,y)
            for i in range(1, len(s)):
                self.show_char(ord(s[i]))
                
    def show_number(self, num, x=0, y=0):
        self.show_string(str(num), x, y)
    
    def scroll_left(self):
        self.setcmd(0x18)

    def scroll_right(self):
        self.setcmd(0x1C)